package org.jvcs.common;


import org.jvcs.common.*;

import java.io.*;
import java.util.*;
import java.net.*;

import org.jvcs.client.core.*;


// This is the common utility method and help/support class
public class osr {

	// Get message from the Ini for printing
	public static String gm(INIFile mini, String section, String key) {
		String rtm = "";
		rtm = mini.getProperty(section, key);
		if (rtm == null) {rtm = "";}
		else{
			rtm = baseCS.expandVar(mini, rtm);
		}
		return rtm;
	}
	
	// HELPER: check variable
	public static boolean isVariable(String inVar) {
		int i = 0;
		int j = 0;
		i = inVar.indexOf("{");
		j = inVar.indexOf("}");
		if ( (i != -1) || (j != -1)) {
			return true;
		}
		return false;
	}

	// INI file related
	public static INIFile loadStdINI(int iniType) {
		String jvcsHome = null;
		String iniFile = null;
		INIFile myIni = new INIFile();
		try {
			Map envMap = System.getenv();
			jvcsHome = (String)envMap.get(G.JVCS_CURR);
			switch(iniType) {
				case G.GlobalINI: iniFile = Utils.stdPath(jvcsHome+"/"+G.GLOBAL_INI_FILE); jvcs.GlobalINIFile = iniFile; break;
				case G.CommonINI: iniFile = Utils.stdPath(jvcsHome+"/"+G.COMMON_INI_FILE); jvcs.CommonINIFile = iniFile; break;
				case G.LocalINI: iniFile = Utils.stdPath(jvcsHome+"/"+G.LOCAL_INI_FILE); jvcs.LocalINIFile = iniFile; break;
				case G.ThisINI: iniFile = Utils.stdPath(jvcsHome+"/"+G.THIS_INI_FILE); jvcs.ThisINIFile = iniFile; break;			
			}
			if (iniFile != null) {
				// Check File exists and create
				File jif = new File(iniFile);
				if (!jif.exists()) {jif.createNewFile();}			
				
				InputStream in = new BufferedInputStream(new FileInputStream(iniFile));
				myIni.load(in);
				in.close();
				return myIni;
			}
		} catch (Exception e) {
			osr.pl("Error: initConfFile => "+e.toString());
			return myIni;
		}
		return myIni;
	}
	
	// END INI file related

	public static void sleep(int n) {
		try {
			Thread.sleep(n*1000);
		} catch (Exception e) {
			pl("Sleep duration problem");
		}
	}
	public static void cs(PrintWriter out){
		out.println("quit");
		out.flush();
	}
	public static void csm(PrintWriter out, String mesg){
		out.println(mesg);
		out.flush();
	}
	public static void pl(String mesg){
		if (!mesg.equals(""))
			System.out.println(""+mesg);
	}
	public static void p(String mesg){
		if (!mesg.equals(""))
			System.out.print(""+mesg);
	}
	public static void e() {
		System.exit(-1);
	}
	public static void ee(String mesg) {
		pl("Error: "+mesg);
		e();
	}
	
	public static String [] sc(String a) {
		String [] r = {};
		r = a.split("\\|");
		return r;
	}
	
	public static String [] pud(String a) {
		String [] r = null;
		String [] u1 = {};
		String [] u2 = {};
		if ((a.indexOf(":") != -1) && (a.indexOf("@") != -1)) {
			u1 = a.split(":");
			u2 = u1[1].split("@");
			r = new String[3];
			r[0] = u1[0];
			r[1] = u2[0];
			r[2] = u2[1];
			return r;
		}
		return r;
		
	}
	
	public static ServerSocket getRandomServerSocket(int s, int e) {
			ServerSocket lss = null;
			int x = 0;
			for(x=s;x<e;x++) {
				try {
					lss = new ServerSocket(x);
					return lss;
				} catch (Exception ex) {
					return lss;
				}
			}
			return lss;
	}
	
	
	// THINKING...
	public static boolean recvFile(String filePath, Socket ds) {
	
		try {
			// RECV
			InputStream clientInputStream = null;
			long startTime = System.currentTimeMillis();
			File f=new File(filePath);
			OutputStream outFile =new FileOutputStream(f);
										
			byte[] buffer = new byte[G.BUFFER_SIZE];
			int read;
			int totalRead = 0;
			clientInputStream = ds.getInputStream();
			while ((read = clientInputStream.read(buffer)) != -1) {
				totalRead += read;
				outFile.write(buffer,0,read);
			}
			ds.close();
			clientInputStream.close();							
											
			outFile.close();
			long endTime = System.currentTimeMillis();
			int mbSize = totalRead/(1024*1024);
			pl(mbSize + " MB received in " + (endTime - startTime) + " ms.");						
			// RECEIVE
			return true;
		} catch (Exception e) {
			pl("Error in recv File: "+e.toString());
			return false;
		}
		// RECV
	}
	
	public static boolean sendFile(String filePath, Socket ds) {
		// SEND
		try {
			final String largeFile = filePath;
			FileInputStream fileInputStream = new FileInputStream(largeFile);
			OutputStream socketOutputStream = ds.getOutputStream();
			long startTime = System.currentTimeMillis();
			byte[] buffer = new byte[G.BUFFER_SIZE];
			int read;
			int readTotal = 0;
			while ((read = fileInputStream.read(buffer)) != -1) {
				socketOutputStream.write(buffer, 0, read);
				readTotal += read;
			}
			socketOutputStream.close();
			fileInputStream.close();
			long endTime = System.currentTimeMillis();
			int sizeMB = readTotal / (1024*1024);
			pl("SERVER: "+sizeMB + " MB written in " + (endTime - startTime) + " ms.");
			return true;
											
		} catch (Exception e) {
			pl("Error: SEND FileTransfer Server: "+e.toString());
			return false;
		}						
		// SEND
	}
}